from fastapi.requests import Request
from pydantic import conint

from utils.drivers.database.models.product import Product
from utils.enums import Sort, TimeKey
from utils.exception import AppException, StatusCode
from utils.g import G
from utils.i18n.i18n import i18n
from utils.pagination import get_pagination
from utils.template.template import template


async def product_list(request: Request, id_: int = 0, page: conint(ge=1) = 1):
    type_name = i18n(request.state.language, "all")

    if id_ == 0:
        products, count = await Product.get(page=page, sort=(TimeKey.UpdateTime, Sort.Desc))
    else:
        type_ = [pt for pt in request.state.product_type_list if pt.id == id_]
        if not type_:
            raise AppException(code=StatusCode.ProductTypeNotFound, detail=f"产品分类`{id_}`不存在。")
        type_ = type_[0]
        type_name = type_.name

        products, count = await Product.get(product_type=id_, sort=(TimeKey.UpdateTime, Sort.Desc), page=page)

    products = [p.model(request.state.language, request.state.product_type_list) for p in products]

    pagination = get_pagination(page, G.pageSize, count)

    return template(request, "product_list.html", context={
        "nav": "products",
        "type_id": id_,
        "type_name": type_name,
        "products": products,
        "pagination": pagination
    })

async def product(request: Request, id_: int):
    p = await Product.get_by_id(id_)
    p = p.model(request.state.language, request.state.product_type_list)
    if not p:
        raise AppException(code=StatusCode.ProductByIdNotFound, detail=f"产品`{id_}`不存在。")

    related_products, _ = await Product.get(not_id=p.id, sort=(TimeKey.UpdateTime, Sort.Desc), product_type=p.product_type_id, page_size=3)
    related_products = [rp.model(request.state.language, request.state.product_type_list) for rp in related_products]

    return template(request, "product.html", context={
        "nav": "products",
        "type_id": p.product_type_id,
        "product": p,
        "related_products": related_products,
    })